<template>
  <div class="card">
    <dv-border-box-11 title="领导动态" :color="['#168BF9', '#112F7C']">
      <!-- 添加平台发布数量统计饼图 -->
      <div class="chart-container">
        <div class="chart-title">渠道统计</div>
        <div class="chart-content">
          <div class="pie-chart-wrapper">
            <div class="pie-chart" ref="pieChart"></div>
            <div class="chart-legend">
              <div
                class="legend-item"
                v-for="(platform, index) in platformData"
                :key="index"
              >
                <div
                  class="legend-color"
                  :style="{ backgroundColor: getChartColor(index) }"
                ></div>
                <div class="legend-text">
                  <span class="platform-name">{{ platform.type }}</span>
                  <span class="platform-stats">{{ platform.value }}篇 </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 原有的领导动态列表 -->
      <div class="table-container">
        <div class="chart-title">最新报道</div>
        <dv-scroll-board
          :config="config"
          style="width: 100%; height: 120px"
          class="custom-scroll-board"
          @click="handleTableClick"
        />
      </div>
    </dv-border-box-11>

    <!-- 文章详情弹窗 -->
    <div v-if="articlePopupVisible" class="cockpit-popup" :style="popupStyle">
      <div class="cockpit-popup-content">
        <div class="popup-header">
          <h2 class="popup-title">{{ selectedArticle.articleName || '文章详情' }}</h2>
          <button class="close-btn" @click="closeArticlePopup">×</button>
        </div>
        <div class="popup-body">
          <div class="article-info">
            <p><strong>渠道:</strong> <span class="data-text">{{ selectedArticle.channel }}</span></p>
            <p><strong>发布时间:</strong> <span class="data-text">{{ formatDateTime(selectedArticle.articleReleaseTime) }}</span></p>
            <p><strong>原文链接:</strong> 
              <a 
                :href="selectedArticle.articleUrl" 
                target="_blank" 
                class="article-link"
                @click.stop
              >
                {{ selectedArticle.articleUrl }}
              </a>
            </p>
          </div>
          <div class="article-preview" v-if="showArticlePreview">
            <iframe 
              :src="selectedArticle.articleUrl" 
              class="article-iframe"
              frameborder="0"
              @load="onIframeLoad"
              @error="onIframeError"
            ></iframe>
            <div v-if="iframeLoading" class="loading-message">正在加载原文...</div>
            <div v-if="iframeError" class="error-message">无法加载原文内容</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { currentPOST } from "api/modules";
import { mapState } from "vuex";

export default {
  components: {
  },
  data() {
    return {
      // 平台发布数据 - 初始化为空，从接口获取
      platformData: [],
      pieChart: null,
      // ECharts 默认颜色系列
      defaultColors: [
        "#5470c6",
        "#91cc75",
        "#fac858",
        "#ee6666",
        "#73c0de",
        "#3ba272",
        "#fc8452",
        "#9a60b4",
        "#ea7ccc",
      ],
      // 文章弹窗相关数据
      articlePopupVisible: false,
      selectedArticle: {},
      iframeLoading: false,
      iframeError: false,
      showArticlePreview: true,
      // 弹窗尺寸配置
      popupSize: {
        width: "80%",
        height: "80%",
      },
      // 存储完整的文章数据
      articlesData: [],
      config: {
        data: [], // 初始化为空数组，从接口获取
        index: false,
        columnWidth: [300, 120, 150], // 调整列宽：标题、渠道、发布时间（移除领导姓名列）
        align: ["left", "center", "center"],
        rowNum: 4,
        waitTime: 2000,
        carousel: "single",
        headerBGC: "rgba(5, 64, 128, 0.8)",
        oddRowBGC: "rgba(5, 64, 128, 0.3)",
        evenRowBGC: "rgba(5, 64, 128, 0.1)",
        headerHeight: 40,
        // header: ["文章标题", "渠道", "发布时间"], // 移除领导姓名表头
      },
    };
  },
  computed: {
    ...mapState(["lastDay"]),
    // 弹窗样式计算属性
    popupStyle() {
      return {
        width: this.popupSize.width,
        height: this.popupSize.height,
        minHeight: "400px",
        maxWidth: "1200px",
        maxHeight: "800px",
      };
    },
  },
  watch: {
    // 监听lastDay的变化，当变化时重新获取数据
    lastDay(newVal) {
      this.getPieData();
      this.getArticleData();
    },
  },
  mounted() {
    this.initPieChart();
    this.getPieData();
    this.getArticleData();
  },
  beforeDestroy() {
    this.clearData();
    if (this.pieChart) {
      this.pieChart.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    clearData() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    getPieData() {
      currentPOST("leftTopPieHome", { lastDay: this.lastDay })
        .then((res) => {
          if (res.code === 0) {
            this.platformData = res.data || [];
            this.updatePieChart();
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("饼图请求失败:", error);
        });
    },

    getArticleData() {
      currentPOST("leftTopArticleHome", {
        lastDay: this.lastDay,
        pageSize: 100,
        current: 1,
      })
        .then((res) => {
          if (res.code === 0) {
            this.processTableData(res.data);
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("文章请求失败:", error);
        });
    },

    // 处理表格数据 - 移除领导姓名
    processTableData(responseData) {
      if (!responseData) {
        return;
      }

      // 根据新的接口数据结构，数据在 responseData.data.data 中
      let articles = [];
      if (responseData.data && Array.isArray(responseData.data.data)) {
        articles = responseData.data.data;
      } else if (Array.isArray(responseData.data)) {
        articles = responseData.data;
      } else if (Array.isArray(responseData)) {
        articles = responseData;
      } else {
        console.warn("无法解析的文章数据格式:", responseData);
        return;
      }

      // 保存完整的文章数据
      this.articlesData = articles;

      // 格式化数据为 dv-scroll-board 需要的格式（移除领导姓名）
      const tableData = articles.map((article) => {
        // 格式化时间，只显示月-日 时:分
        const releaseTime = this.formatDateTime(article.articleReleaseTime);

        // 调整顺序：标题、渠道、发布时间（移除领导姓名）
        return [
          article.articleName || "--", // 文章标题（第一列）
          article.channel || "--", // 渠道（第二列）
          releaseTime || "--", // 发布时间（第三列）
        ];
      });

      // 更新表格配置
      this.config = {
        ...this.config,
        data: tableData,
      };
    },

    // 处理表格点击事件
    handleTableClick(event) {
      if (event && event.rowIndex >= 0) {
        const rowIndex = event.rowIndex;
        const article = this.articlesData[rowIndex];
        
        if (article && article.articleUrl) {
          this.openArticlePopup(article);
        } else {
          console.warn('文章数据不完整，无法打开详情');
        }
      }
    },

    // 打开文章弹窗
    openArticlePopup(article) {
      this.selectedArticle = { ...article };
      this.articlePopupVisible = true;
      this.iframeLoading = true;
      this.iframeError = false;
    },

    // 关闭文章弹窗
    closeArticlePopup() {
      this.articlePopupVisible = false;
      this.selectedArticle = {};
      this.iframeLoading = false;
      this.iframeError = false;
    },

    // iframe加载完成
    onIframeLoad() {
      this.iframeLoading = false;
      this.iframeError = false;
    },

    // iframe加载错误
    onIframeError() {
      this.iframeLoading = false;
      this.iframeError = true;
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return "";

      try {
        // 处理可能的字符串格式
        let dateStr = dateTimeStr;
        if (dateStr.includes("T")) {
          dateStr = dateStr.replace("T", " ").split(".")[0];
        }

        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
          return dateTimeStr;
        }

        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const hours = date.getHours().toString().padStart(2, "0");
        const minutes = date.getMinutes().toString().padStart(2, "0");

        return `${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return dateTimeStr;
      }
    },

    // 根据索引获取颜色
    getChartColor(index) {
      return this.defaultColors[index % this.defaultColors.length];
    },

    // 初始化饼图
    initPieChart() {
      this.$nextTick(() => {
        if (this.$refs.pieChart) {
          this.pieChart = echarts.init(this.$refs.pieChart);
          window.addEventListener("resize", this.handleResize);
        }
      });
    },

    // 更新饼图数据
    updatePieChart() {
      if (!this.pieChart || !this.platformData.length) return;

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c}篇 ({d}%)",
        },
        legend: {
          show: false,
        },
        color: this.defaultColors,
        series: [
          {
            name: "平台发布数量",
            type: "pie",
            radius: "70%",
            center: ["50%", "50%"],
            avoidLabelOverlap: true,
            itemStyle: {
              borderColor: "rgba(5, 64, 128, 1)",
              borderWidth: 2,
            },
            label: {
              show: true,
              formatter: "{b}\n{d}%",
              color: "#a0d2ff",
              fontSize: 10,
              fontWeight: "normal",
              lineHeight: 14,
            },
            emphasis: {
              scale: true,
              scaleSize: 5,
              label: {
                show: true,
                fontSize: 12,
                fontWeight: "bold",
                color: "#ffffff",
              },
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 8,
              smooth: true,
              lineStyle: {
                color: "rgba(186, 231, 255, 0.6)",
                width: 1,
              },
            },
            data: this.platformData.map((item, index) => ({
              value: item.value,
              name: item.type,
            })),
          },
        ],
      };

      this.pieChart.setOption(option);
    },

    handleResize() {
      if (this.pieChart) {
        this.pieChart.resize();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-top: 30px;
  height: 450px;
  display: flex;
  justify-content: center;
}

.chart-container {
  padding: 15px 30px 0;
  margin-top: 40px;
}

.chart-title {
  color: #bae7ff;
  font-size: 16px;
  font-weight: 500;
  margin-block: 10px;
  flex-shrink: 0;
}

.chart-content {
  height: 190px;
  margin-top: -20px;
}

.pie-chart-wrapper {
  display: flex;
  height: 100%;
  align-items: center;
}

.pie-chart {
  width: 300px;
  height: 180px;
  flex-shrink: 0;
}

.chart-legend {
  flex: 1;
  padding-left: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  flex-shrink: 0;
}

.legend-text {
  display: flex;
}

.platform-name {
  color: #a0d2ff;
  font-size: 12px;
  line-height: 1.2;
}

.platform-stats {
  color: #fff;
  font-size: 11px;
  opacity: 0.8;
  line-height: 1.2;
}

.table-container {
  height: 55%;
  padding: 0px 30px;
}

/* 文章弹窗样式 */
.cockpit-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(135deg, #1a3a5f 0%, #2d5278 100%);
  border: 1px solid #1890ff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  z-index: 1000;
  overflow: hidden;
}

.cockpit-popup-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}




.popup-body {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.article-info {
  margin-bottom: 20px;
  p {
    margin: 8px 0;
    display: flex;
    align-items: center;
  }
  strong {
    color: #bae7ff;
    margin-right: 8px;
    min-width: 80px;
  }
}

.article-link {
  color: #1890ff;
  text-decoration: none;
  word-break: break-all;
  &:hover {
    text-decoration: underline;
    color: #40a9ff;
  }
}

.article-preview {
  position: relative;
  height: 540px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 15px;
  flex: 1;
}

.article-iframe {
  width: 100%;
  height: 100%;
  background: white;
}

.loading-message, .error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #bae7ff;
  font-size: 16px;
  text-align: center;
}

.error-message {
  color: #ff7875;
}

/* 滚动表格点击样式优化 */
:deep(.custom-scroll-board) {
  .row-item {
    cursor: pointer;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: rgba(24, 144, 255, 0.2) !important;
    }
  }
  
  .header {
    cursor: default !important;
  }
}
</style>